package org.setamv.springcloud.controller;

import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCommandKey;
import org.setamv.springcloud.entity.User;
import org.setamv.springcloud.feignclient.UserServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceClient userServiceClient;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public User getUser(@PathVariable String id) {
        User user = userServiceClient.getUser(id);
        return user;
    }

    /**
     * 测试Hystrix超时回退
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/slowly", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public User getUserSlowly(@PathVariable String id) throws Exception {
        User user = userServiceClient.getUserSlowly(id);
        HystrixCircuitBreaker breaker = HystrixCircuitBreaker.Factory.getInstance(HystrixCommandKey.Factory.asKey("UserServiceClient#getUserSlowly(String)"));
        System.out.println("is breaker open ? " + breaker.isOpen());
        return user;
    }

    @RequestMapping(value = "/batch/{ids}")
    public List<User> getUsers(@PathVariable List<String> ids) {
        String joinedIds = String.join(",", ids);
        List<User> users = userServiceClient.getUsers(joinedIds);
        return users;
    }
}
